package com.example.translateappjava.Activity.HomeFragmentActivity.Forum;

import android.annotation.SuppressLint;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.example.translateappjava.R;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.translateappjava.Utils.MockDataUtil;
import com.example.translateappjava.Utils.Post;
import com.example.translateappjava.Adapter.PostAdapter;
import com.example.translateappjava.Adapter.SearchHistoryAdapter;
import java.util.ArrayList;
import java.util.List;

public class ForumSearchActivity extends AppCompatActivity implements PostAdapter.OnPostClickListener, SearchHistoryAdapter.OnSearchHistoryClickListener {

    private EditText etSearch;
    private RecyclerView rvSearchResults;
//    private TextView tvNoResults;
    private TextView tvSearchHistory;
    private RecyclerView rvSearchHistory;
    private List<Post> allPosts; // 这个列表将从mock json加载
    private View layoutNoResultsContainer; // 用于控制整个“无结果”区域
    private TextView tvNoResultsMessage;   // 用于显示“未找到...”消息
    private PostAdapter searchResultAdapter;
    private SearchHistoryAdapter searchHistoryAdapter;

    private List<Post> searchResults;
    private List<String> searchHistory;

    private String currentSearchQuery = "";
    private View recommends;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_search);

        setupToolbar();
        initViews();
        initData();
        setupRecyclerViews();
        setupSearchListener();
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("搜索帖子");
        }
    }

    private void initViews() {
        etSearch = findViewById(R.id.et_search);
        rvSearchResults = findViewById(R.id.rv_search_results);
        layoutNoResultsContainer = findViewById(R.id.layout_no_results_container); // 获取LinearLayout
        tvNoResultsMessage = findViewById(R.id.tv_no_results_message);         // 获取内部的TextView
        tvSearchHistory = findViewById(R.id.tv_search_history);
        rvSearchHistory = findViewById(R.id.rv_search_history);
        recommends = findViewById(R.id.recommends);
    }

    private void initData() {
        // 初始化所有帖子数据（实际项目中应该从数据库或网络获取）
        allPosts = MockDataUtil.loadMockPosts(this, "mock_posts_health.json");
        if (allPosts == null) {
            allPosts = new ArrayList<>(); // 防止null pointer
        }
        searchResults = new ArrayList<>();
        searchHistory = new ArrayList<>();

        // 加载搜索历史（实际项目中应该从SharedPreferences加载）
        loadSearchHistory();
    }

    private void setupRecyclerViews() {
        // 搜索结果RecyclerView
        searchResultAdapter = new PostAdapter(searchResults, this);
        rvSearchResults.setLayoutManager(new LinearLayoutManager(this));
        rvSearchResults.setAdapter(searchResultAdapter);

        // 搜索历史RecyclerView
        searchHistoryAdapter = new SearchHistoryAdapter(this, searchHistory);
        rvSearchHistory.setLayoutManager(new LinearLayoutManager(this));
        rvSearchHistory.setAdapter(searchHistoryAdapter);

        updateSearchHistoryVisibility();
    }

    private void setupSearchListener() {
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                currentSearchQuery = s.toString().trim();
                performSearch(currentSearchQuery);
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        // 搜索框获得焦点时显示搜索历史
        etSearch.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus && TextUtils.isEmpty(currentSearchQuery)) {
                showSearchHistory();
            }
        });
    }

    private void performSearch(String query) {
        if (TextUtils.isEmpty(query)) {
            showSearchHistory();
            return;
        }

        searchResults.clear();

        // 搜索标题和内容
        for (Post post : allPosts) {
            if (post.getTitle().toLowerCase().contains(query.toLowerCase()) ||
                    post.getContent().toLowerCase().contains(query.toLowerCase()) ||
                    post.getCategory().toLowerCase().contains(query.toLowerCase()) ||
                    post.getUsername().toLowerCase().contains(query.toLowerCase())) {
                searchResults.add(post);
            }
        }

        updateSearchResults();
    }

    private void updateSearchResults() {
        hideSearchHistory();

        if (searchResults.isEmpty() && !TextUtils.isEmpty(currentSearchQuery)) {
            rvSearchResults.setVisibility(View.GONE);
            layoutNoResultsContainer.setVisibility(View.VISIBLE);
            tvNoResultsMessage.setText("未找到包含 \"" + currentSearchQuery + "\" 的帖子");
        } else {
            rvSearchResults.setVisibility(View.VISIBLE);
            layoutNoResultsContainer.setVisibility(View.GONE);
            recommends.setVisibility(View.GONE);
            // 如果之前设置了文本，可以在这里重置为默认值，或者不操作
            // tvNoResultsMessage.setText("未找到搜索结果"); // 可选
        }
        searchResultAdapter.notifyDataSetChanged();
    }

    private void showSearchHistory() {
        rvSearchResults.setVisibility(View.GONE);
        layoutNoResultsContainer.setVisibility(View.GONE);
        updateSearchHistoryVisibility();
    }


    private void hideSearchHistory() {
        tvSearchHistory.setVisibility(View.GONE);
        rvSearchHistory.setVisibility(View.GONE);
    }

    private void updateSearchHistoryVisibility() {
        if (searchHistory.isEmpty()) {
            tvSearchHistory.setVisibility(View.GONE);
            rvSearchHistory.setVisibility(View.GONE);
            recommends.setVisibility(View.GONE);
        } else {
            tvSearchHistory.setVisibility(View.VISIBLE);
            rvSearchHistory.setVisibility(View.VISIBLE);
            recommends.setVisibility(View.VISIBLE);
            searchHistoryAdapter.notifyDataSetChanged();
        }
    }

    private void addToSearchHistory(String query) {
        if (TextUtils.isEmpty(query)) {
            return;
        }

        // 移除重复项
        if (searchHistory.contains(query)) {
            searchHistory.remove(query);
        }

        searchHistory.add(0, query);

        // 限制搜索历史数量
        if (searchHistory.size() > 10) {
            searchHistory.remove(searchHistory.size() - 1);
        }

        saveSearchHistory();
        updateSearchHistoryVisibility();
    }

    private void loadSearchHistory() {
        // 实际项目中应该从SharedPreferences加载
        // 这里添加一些示例数据
        searchHistory.add("😎大英警玩弄大英帝");
        searchHistory.add("🐭老鼠生病了要喝老鼠药么");
        searchHistory.add("☠️二氧化氢有剧毒");
    }

    private void saveSearchHistory() {
        // 实际项目中应该保存到SharedPreferences
    }

    @Override
    public void onPostClick(Post post) {
        // 添加到搜索历史
        if (!TextUtils.isEmpty(currentSearchQuery)) {
            addToSearchHistory(currentSearchQuery);
            rvSearchResults.setVisibility(View.GONE);
        }

        // 跳转到帖子详情页面
        Intent intent = new Intent(this, PostDetailActivity.class);
        intent.putExtra("post_title", post.getTitle());
        intent.putExtra("post_content", post.getContent());
        intent.putExtra("post_username", post.getUsername());
        intent.putExtra("post_time", post.getTime());
        intent.putExtra("post_category", post.getCategory());
        intent.putExtra("post_like_count", post.getLikeCount());
        intent.putExtra("post_comment_count", post.getCommentCount());
        startActivity(intent);
    }

    @Override
    public void onSearchHistoryClick(String historyItem) {
        etSearch.setText(historyItem);
        etSearch.setSelection(historyItem.length());
        performSearch(historyItem);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
    }
}